package mmc.ui;

import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;

import mmc.Client;
import mmc.resource.Sprite2D;
import static mmc.resource.Text12p.glText12p;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.input.Keyboard.*;

public class Menu extends Window {
	private Sprite2D background;
	private int item=0;
	
	public Menu(float pos_x, float pos_y, float size_x, float size_y) {
		super(pos_x, pos_y, size_x, size_y);
		this.name = "Menu";
		background = new Sprite2D("mmc/resource/data/menu.png");
		
		KeyBinding.addWindowShortcut(this.name, KEY_ESCAPE, this);		
	}

	@Override
	public void render() {
		if(!open) return;
		
		glColor4f(1,1,1,1);
		background.draw2f(x, y, width, height);	
		
		int i = 0;
		
		for (Window win : UI.windows) {
			glColor4f(1,1,1,1);
			writeMiddle(win.name, x, y+0.1f+0.04f*i);
			
			i++;
		}
		
		
		if(Mouse.getDX() != 0 | Mouse.getDY() != 0){
			float my = 1-(float)Mouse.getY()/Client.client.getSize().height;
			
			int help = (int)((my-y-0.1f)*100/4);
			item = (help >= 0 && help < i)?help:item;
		}
		
		if(Mouse.isButtonDown(0))
		{
			float my = 1-(float)Mouse.getY()/Client.client.getSize().height;
			
			int help = (int)((my-y-0.1f)*100/4);
			if(help >= 0 && help < i)
				Client.client.ui.openWindow(UI.windows.get(item));
		}	
		
		glColor3f(1,0,0);
		GL11.glBegin(GL11.GL_LINES);			//Header tile
		GL11.glVertex2f(x+width*1/5, y+0.13f+0.04f*item);
		GL11.glVertex2f(x+width*4/5, y+0.13f+0.04f*item);
		GL11.glEnd();			
	}
	
	public void writeMiddle(String text, float x, float y)
	{
		x += width/2 - ((float)text.length()/2)*0.012f;
		glText12p(text, x, y); 
	}
	
	@Override
	public void forwardKey(int key, char ch)
	{
		switch(key)
		{
			case KEY_RETURN:
				Client.client.ui.openWindow(UI.windows.get(item)); //Client.client.ui.bindingWindow);
				break;
			case KEY_DOWN:
				item++;
				item = Math.min(item, UI.windows.size()-1);
				break;
			case KEY_UP:
				item--;
				item = Math.max(item, 0);
				break;
		}
	}
}
